package cn.com.infcn.spider.web.job;

import java.util.List;

import org.apache.log4j.Logger;
import org.nutz.mvc.NutConfig;

import com.mongodb.DBCursor;
import com.mongodb.DBObject;

import cn.com.infcn.spider.SchedulerManager;
import cn.com.infcn.spider.domain.Job;
import cn.com.infcn.spider.util.MongoDao;

/**
 * 定时检查job
 * 
 * @author ansj
 *
 */
public class CheckJob extends Thread {

	private static final Logger LOG = Logger.getLogger(CheckJob.class);

	private MongoDao mongoDao = null;

	public CheckJob(NutConfig nc) {
		this.mongoDao = nc.getIoc().get(MongoDao.class, "mongoDao");
	}

	@Override
	public void run() {
		while (true) {
			;

			try (DBCursor find = mongoDao.getCollection("job").find()) {
				List<DBObject> array = find.toArray();
				for (DBObject dbObject : array) {
					try {
						Integer status = (Integer) dbObject.get("status");

						String jobName = (String) dbObject.get("name");

						if (status != 1) {
							SchedulerManager.shutDwon(jobName);
							continue;
						}

						Job job = SchedulerManager.getJob(jobName);

						if (job != null && !job.getUpdateTime().equals(dbObject.get("updateTime"))) {
							SchedulerManager.flush(jobName);
							LOG.info(jobName + " has changed now flushed it !");
						} else if (job == null) {
							SchedulerManager.flush(jobName);
							LOG.info(jobName + " find it mow to run !");
						} else {
							LOG.info(jobName + " status is ok!");
						}

					} catch (Exception e) {
						e.printStackTrace();
					}

				}

			}

			try {
				Thread.sleep(1000L);
			} catch (InterruptedException e) {
				e.printStackTrace();
				break;
			}
		}

	}

}
